<template>
  <div class="json-tabs">
    <n-card>
      <n-tabs
        v-model:value="activeTab"
        type="card"
        addable
        closable
        @add="addTab"
        @close="closeTab"
        :max="maxTabs"
        class="tabs-wrapper"
      >
        <n-tab-pane
          v-for="tab in tabs"
          :key="tab.id"
          :name="tab.id"
          :tab="tab.title"
          :closable="tabs.length > 1"
        >
          <div class="tab-content">
            <JsonFormat 
              :ref="el => { if (el) formatRefs[tab.id] = el }"
              :initial-input="tab.inputJson"
              :initial-formatted="tab.formattedJson"
              @content-change="(input, formatted) => updateTabContent(tab.id, input, formatted)"
            />
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import JsonFormat from './JsonFormat.vue'

interface Tab {
  title: string
  id: string
  inputJson: string
  formattedJson: string
}

const maxTabs = 10
const formatRefs = reactive<Record<string, any>>({})

const generateId = () => `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

const firstTab = {
  title: 'JSON 1',
  id: generateId(),
  inputJson: '',
  formattedJson: ''
}

const tabs = ref<Tab[]>([firstTab])
const activeTab = ref(firstTab.id)

const updateTabContent = (tabId: string, input: string, formatted: string) => {
  const tab = tabs.value.find(t => t.id === tabId)
  if (tab) {
    tab.inputJson = input
    tab.formattedJson = formatted
  }
}

const addTab = () => {
  if (tabs.value.length >= maxTabs) return
  
  const newTab = {
    title: `JSON ${tabs.value.length + 1}`,
    id: generateId(),
    inputJson: '',
    formattedJson: ''
  }
  tabs.value.push(newTab)
  activeTab.value = newTab.id
}

const closeTab = (tabId: string) => {
  if (tabs.value.length <= 1) return
  
  const index = tabs.value.findIndex(tab => tab.id === tabId)
  if (index === -1) return

  tabs.value.splice(index, 1)
  delete formatRefs[tabId]
  
  tabs.value.forEach((tab, idx) => {
    tab.title = `JSON ${idx + 1}`
  })
  
  if (activeTab.value === tabId) {
    activeTab.value = tabs.value[tabs.value.length - 1].id
  }
}
</script>

<style scoped>
.json-tabs {
  height: 100%;
}

.tab-content {
  height: 100%;
}

:deep(.n-tabs) {
  height: 100%;
}

:deep(.n-tabs-content) {
  height: calc(100% - 44px);
  overflow-y: auto;
}

:deep(.n-tab-pane) {
  height: 100%;
}

:deep(.n-tabs-nav) {
  padding: 0 8px;
}

:deep(.n-tabs-tab) {
  padding: 4px 20px;
}

:deep(.n-tabs-tab-pad) {
  width: 36px;
}
</style>